import axios from 'axios'
// import store from '../store'
import { Message, Loading } from 'element-ui'
import config from 'api/config'

function logout(){
  localStorage.clear()
  // 这边清除 store数据 要验证下
  // store.replaceState({})
  setTimeout(()=>{
    window.location.reload()
  }, 500)
}

axios.defaults.timeout = 10000

var instance1 = axios.create({
  withCredentials: true,
  baseURL: config.serverUrl
})

// http request 拦截器
instance1.interceptors.request.use(
  config => {
    let tokenInfo = localStorage.getItem('userData')
    if (tokenInfo) {
      let token = JSON.parse(tokenInfo).token
      config.headers.token = token
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// http response 拦截器
instance1.interceptors.response.use(
  response => {
    return response
  },
  error => {
    return Promise.reject(error)
  }
)

/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function get (url, params) {
  return new Promise((resolve, reject) => {
    instance1.get(url, {
      params: params
    })
    .then(
      (res) => resSuccess(resolve, reject, res), 
      (err) => resError(resolve, reject, err)
    )
  })
}

/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

export function post (url, data = {}) {
  return new Promise((resolve, reject) => {
    instance1.post(url, data)
      .then(
        (res) => resSuccess(resolve, reject, res), 
        (err) => resError(resolve, reject, err)
      )
  })
}

// 请求成功的处理
function resSuccess(resolve, reject, res) {
  let data = res.data
  if(data.rCode === '200'){
    resolve(data)
  } else {
    if(data.rCode === '90003' || data.rCode==='90005') {
      Message.error('登录过期，请重新登录');
      logout()
    }else{
      Message.error(data.rMsg)
      reject(data)
    }
  }
}
// 错误处理
function resError(resolve, reject, err) {
  Message.error('请求错误请重试')
  reject(err)
}


// 这层是错误拦截
export async function postWithLoading (url, data) {
  let instance = Loading.service({
    body: true,
    lock: true,
    background: 'rgba(0,0,0,0.3)',
    text: '拼命加载中...'
  })
  try {
    let res = await post(url, data)
    instance.close()
    return res
  } catch (error) {
    instance.close()
    throw Error(error)
  }
}

export function catchError(){}